package com.example.demo.controller;

import com.example.demo.mapper.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author :蕉绿
 * @Date : 2023/2/22 9:27
 * @Version : V1.0
 * @Description :
 */

@Controller
@ResponseBody
@RequestMapping("/user")
public class userController {
    //post get 请求
    @GetMapping("/get")
    public String sayHi() {
        return "Hi! SpringMVC!";
    }
    @PostMapping("/post")
    public String sayHi2() {
        return "post";
    }

    //获取单个参数
    @RequestMapping("/param")
    public String getParam(String name) {
        return name;
    }

    //传递对象
    @RequestMapping("/getuser")
    public String getUser(User user) {
        return user.getId() + "   |   " + user.getName();
    }
    //表单参数的传递/传递多个参数  后端参数重命名
    @RequestMapping("/form")
    public String getParams(@RequestParam(value = "n",required = false) String name,
                            @RequestParam(value = "p",required = false) String password) {

        System.out.println("名字: " + name);
        System.out.println("密码: " + password);
        return "/user.html";
    }
    //接受JSON 对象
    @PostMapping("/json")
    public Object getJson(@RequestBody User user) {
        System.out.println("user对象:" + user);
        return "redirect:/user.html";
    }

    //获取URL中的参数
    @RequestMapping("/login/{name}/{password}")
    public String getUrl(@PathVariable("name")String name,@PathVariable("password")String password) {

        return name + " | " + password;
    }

    //文件上传
    @RequestMapping("/file")
    public String param(@RequestPart("myfile")MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String path = "D:\\logs"+ "\\" +UUID.randomUUID().toString().replace("-","") + fileName;
        file.transferTo(new File(path));
        return path + " 上传成功!";

    }
}
